import {tokenAlive} from "@/common/utils";

module.exports = {
    methods: {
        //更改头像
        avatarUpload(file) {
            const tempFilePaths = file.detail.avatarUrl;
            this.$http.updateFile('/uni-app/upload', 'file',
                tempFilePaths)
                .then(res => {
                    const resData = JSON.parse(res.data);
                    this.ownerAvatar = resData.data;
                    //修改数据库头像
                    let owner = {
                        ownerPhoneNumber: uni.getStorageSync('ownerPhoneNumber'),
                        ownerPortrait: this.ownerAvatar
                    };
                    this.$http.put('/uni-app/ownerAvatar', owner).then(res => {
                        this.$refs.uToast.show({
                            type: 'success',
                            message: "修改成功！",
                            iconUrl: 'static/uToastIcon/success.png',
                        });
                    });
                });
        },

        //跳转登录按钮
        routerLogin() {
            uni.redirectTo({url: '/pages/login/Login'})
        },

        //退出登录
        outLogin() {
            uni.removeStorageSync('ownerName');
            uni.removeStorageSync('token');
            uni.removeStorageSync('ownerId');
            uni.removeStorageSync('ownerStatus')
            uni.reLaunch({url: '/pages/index/index'})
        },
    },

    onLoad() {
        // 业主昵称存在 => 比对token时间 => 获取对应业主头像
        if (uni.getStorageSync('ownerName') !== '' && uni.getStorageSync('ownerName') !== null) {
            if (tokenAlive()) {
                //获取保存的业主昵称
                this.ownerName = uni.getStorageSync('ownerName');
                //获取头像
                const ownerPhoneNumber = uni.getStorageSync('ownerPhoneNumber');
                this.$http.get('/uni-app/ownerAvatar?ownerPhoneNumber=' + ownerPhoneNumber)
                    .then(res => {
                        this.ownerAvatar = res.data.data;
                    });
            } else {
                uni.removeStorageSync('ownerName');
                uni.removeStorageSync('token');
                uni.removeStorageSync('ownerId');
                uni.showToast({
                    title: '登录已过期',
                    icon: 'error', // 提示图标：success/none
                    duration: 1000, // 持续时间，单位为毫秒
                    mask: false, // 是否显示透明蒙层，防止触摸穿透，默认为false
                    //回调刷新当前页面
                    complete() {
                        uni.reLaunch({url: '/pages/my/MyView'});
                    },
                });
            }
        }
    },

    data() {
        return {
            ownerName: '',/* 登录用户名 */
            ownerAvatar: '',
        }
    },
}
